package team.yidong.fenda.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import team.yidong.fenda.entity.SysRolePermission;
import team.yidong.fenda.entity.SysUser;
import team.yidong.fenda.entity.SysUserPermission;
import team.yidong.fenda.repository.SysRolePermissionRepository;
import team.yidong.fenda.repository.SysUserPermissionRepository;
import team.yidong.fenda.repository.SysUserRepository;

import java.util.List;

/**
 * Created by xuanlong on 2017/10/21.
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    SysUserRepository sysUserRepository;
    @Autowired
    SysRolePermissionRepository sysRolePermissionRepository;
    @Autowired
    SysUserPermissionRepository sysUserPermissionRepository;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入权限控制");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String userName = (String) principalCollection.getPrimaryPrincipal();
        SysUser sysUser = sysUserRepository.findByUserName(userName);
        Integer sysUserRoleId = sysUser.getSysUserRoleId();
        List<SysRolePermission> sysRolePermissionList = sysRolePermissionRepository.findByRoleId(sysUserRoleId);
        for (SysRolePermission sysRolePermission : sysRolePermissionList) {
            SysUserPermission sysUserPermission = sysUserPermissionRepository.findOne(sysRolePermission.getPermissionId());
            simpleAuthorizationInfo.addStringPermission(sysUserPermission.getPermission());
        }

        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        String userName = (String) authenticationToken.getPrincipal();
        SysUser sysUser = sysUserRepository.findByUserName(userName);
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        if (sysUser != null) {
            simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    sysUser.getUserName(),
                    sysUser.getPassword(),
                    getName()
            );

        }
        return simpleAuthenticationInfo;
    }


}



